#include "NetConfig.h"
#include "NetCommon.h"

#include <iostream>
#include <fstream>
#include <boost/config.hpp>
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/lexical_cast.hpp>

namespace pod = boost::program_options::detail;

bool NetConfig::Open(const char* filename)
{
    std::ifstream config(filename);
    if(!config) {
        std::cerr<<"error"<<std::endl;
        return false;
    }

    std::set<std::string> options;
    options.insert("*");
    try
    {
        for (pod::config_file_iterator i(config, options), e ; i != e; ++i)
        {
            std::cout << i->string_key <<" "<<i->value[0] << std::endl;
            parameters_[i->string_key] = i->value[0];
        }
    }
    catch(std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << std::endl;
        false;
    }

    return true;
}

const char* NetConfig::GetString(const char* section, const char* key,
                                 const char* defaultValue) const
{
    std::string keyStr(section);
    keyStr += ".";
    keyStr += key;
    AUTO(iter, parameters_.find(keyStr.c_str()));
    if (iter == parameters_.end()) {
        return defaultValue;
    } else {
        return iter->second.c_str();
    }
}

int NetConfig::GetInt(const char* section, const char* key, int defaultValue) const
{
    std::string str = GetString(section, key);
    if (str.empty()) {
        return defaultValue;
    } else {
        try {
            return boost::lexical_cast<int>(str);
        } catch (boost::bad_lexical_cast& e) {
            std::cout << e.what() << std::endl;
            return defaultValue;
        }
    }
}

